#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>//bool:true\false
#include "L_queue.h"

/*初始化链式队列*/
L_Queue_t* InitQueue(void)
{
    L_Queue_t *queue = (L_Queue_t *)malloc(sizeof(L_Queue_t));
    if (!queue)
    {
        return NULL;
    }
    
    queue->front = (Node *)malloc(sizeof(Node));
    if (queue->front == NULL)
    {
        free(queue);
        return NULL;
    }
    
    queue->rear =  queue->front;
    queue->front->next = NULL;
    queue->rear->next = NULL;
    return queue;
}

/*销毁队列*/
void DestroyQueue(L_Queue_t **queue)
{
    if (!(*queue))
    {
        return;
    }
    
    Node *temp = (*queue)->front;
    while (temp)
    {
        Node *tempp = temp->next;
        free(temp);
        temp = tempp;
    }

    free(*queue);
    *queue = NULL;
    
}

/*队列是否为空*/
bool IsQueueEmpty(L_Queue_t *queue)
{
    if (!queue)
    {
        exit(-1);
    }
    
    if (queue->front->next == NULL)
    {
        printf("队列为空\n");
        return true;
    }
    
    return false;
}

/*入队*/
L_Queue_t* enQueue(L_Queue_t *queue,ElemType data)
{

    if (!queue)
    {
       return NULL;
    }
    
    Node *new_node = (ElemType *)malloc(sizeof(ElemType));
    if (!new_node)
    {
        return queue;
    }
    
    new_node->data = data;
    new_node->next = NULL;

    queue->rear->next = new_node;
    queue->rear = new_node;

    printf("入队元素为%d\n",(int)data);
    return queue;
}

/*出队*/
ElemType deQueue(L_Queue_t *queue)
{
    if (IsQueueEmpty(queue))
    {
        exit(-1);
    }

    Node *head = queue->front->next;
    ElemType data = head->data;

    queue->front->next = head->next;

    free(head);

    printf("出队元素为%d\n",(int)data);
    return data;
}


/*取队首元素*/
ElemType getHead(L_Queue_t *queue)
{
    if (IsQueueEmpty(queue))
    {
        exit(-1);
    }
    
    ElemType data = queue->front->next->data;
    printf("队首元素为%d\n",data);
    return data;
}

/*取队尾元素*/
ElemType getTail(L_Queue_t *queue)
{
    if (IsQueueEmpty(queue))
    {
        exit(-1);
    }
    
    ElemType data = queue->rear->data;
    printf("队尾元素为%d\n",data);
    return data;
}

L_Queue_t *queue = NULL;
int main(int argc, char const *argv[])
{
    queue = InitQueue();

    enQueue(queue,20);
    getHead(queue);
    getTail(queue);
    enQueue(queue,20);
    enQueue(queue,20);
    enQueue(queue,30);
    enQueue(queue,40);
    enQueue(queue,80);
    getHead(queue);
    getTail(queue);
    deQueue(queue);
    deQueue(queue);
    deQueue(queue);
    deQueue(queue);
    deQueue(queue);
    deQueue(queue);
    deQueue(queue);
    return 0;
}
